import android.content.Context
import android.util.Log
import android.widget.ImageView
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bumptech.glide.Glide
import com.example.demo1.reposity.ArticleItem
import com.example.demo1.reposity.ArticleListResponse
import com.example.demo1.reposity.ArticleReadList
import com.example.demo1.reposity.ArticleTypeListResponse
import com.example.demo1.reposity.Content
import com.example.demo1.reposity.Data
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.IdentityHashMap


class ArticleViewModel : ViewModel() {
    private val apiService: ApiService =
        ApiService.create("sid=OFvEbpyl4PyKkc/cSjl2tW3g5Ga/z5DPSQRGQn8mJBs=")
    private val apiService1: ApiService =
        ApiService.create("sid=i5VMMK2c7EEm5qK597kJeDqrel7NKCRqSQRGQn8mJBs=")
    private val _typeListStateFlow = MutableStateFlow<List<String>>(emptyList())
    val typeListStateFlow: StateFlow<List<String>> = _typeListStateFlow
    private val _selectListStateFlow = MutableStateFlow<List<String>>(emptyList())
    val selectListStateFlow: StateFlow<List<String>> = _selectListStateFlow
    private val _articleListStateFlow = MutableStateFlow<List<ArticleItem>?>(null)
    val articleListStateFlow: StateFlow<List<ArticleItem>?> = _articleListStateFlow

    private val _articleReadListStateFlow = MutableStateFlow<List<Content>>(emptyList())
    val articleReadListStateFlow: StateFlow<List<Content>> = _articleReadListStateFlow


    fun fetchData() {
        viewModelScope.launch {
            fetchArticleTypeList()
            fetchSelectList()
            fetchArticleList(650, 1)
        }

    }

    fun fetchReadArticleData() {
        viewModelScope.launch {
            fetchReadArticleList()
        }

    }


    fun refreshSelectList() {
        viewModelScope.launch {

            fetchSelectList()
        }
    }

    fun refreshArtitleList(lexile: Int, typeId: Int) {
        viewModelScope.launch {
            fetchArticleList(lexile, typeId)
        }
    }


    private suspend fun fetchArticleTypeList() {
        try {
            val response = withContext(Dispatchers.IO) {
                apiService.getArticleTypeList().execute()
            }
            if (response.isSuccessful) {
                val newList =
                    listOf("精选阅读") + (response.body()?.data?.map { it.type } ?: emptyList())
                _typeListStateFlow.value = newList
            } else {
                Log.e(
                    "ArticleViewModel",
                    "fetchArticleTypeList failed: ${response.code()} - ${response.message()}"
                )
            }
        } catch (e: Exception) {
            Log.e("ArticleViewModel", "fetchArticleTypeList exception: $e")
        }
    }


    private suspend fun fetchSelectList() {
        try {
            val response = withContext(Dispatchers.IO) {
                apiService.getSelectList().execute()
            }
            if (response.isSuccessful) {
                _selectListStateFlow.value = response.body()?.data ?: emptyList()
            } else {
                Log.e(
                    "ArticleViewModel",
                    "fetchSelectList failed: ${response.code()} - ${response.message()}"
                )
            }
        } catch (e: Exception) {
            Log.e("ArticleViewModel", "fetchSelectList exception: $e")
        }
    }

    private suspend fun fetchReadArticleList() {
        try {
            val response = withContext(Dispatchers.IO) {
                apiService1.getReadArticleList().execute()
            }
            if (response.isSuccessful) {
                _articleReadListStateFlow.value = response.body()?.data?.contentList?: emptyList()
                Log.e(
                    "ArticleViewModel",
                    "fetchSelectList success: ${response.body()?.data} - ${response.message()}"
                )
            } else {
                Log.e(
                    "ArticleViewModel",
                    "fetchSelectList failed: ${response.body()?.data} - ${response.message()}"
                )
            }
        } catch (e: Exception) {
            Log.e("ArticleViewModel", "fetchSelectList exception: $e")
        }
    }

    private suspend fun fetchArticleList(lexile: Int, typeId: Int, page: Int = 1, size: Int = 10) {
        try {
            val response = withContext(Dispatchers.IO) {
                apiService.getArticleList(lexile, typeId, page, size).execute()
            }
            if (response.isSuccessful) {
                if (response.body()?.data!!.list.isNotEmpty()) {
                    _articleListStateFlow.value = null
                    _articleListStateFlow.value = response.body()?.data!!.list
                    Log.e(
                        "ArticleViewModel",
                        "fetchArticleList success: ${response.body()!!.data.list} "
                    )
                } else {
                    _articleListStateFlow.value = null
                }

            } else {
                Log.e(
                    "ArticleViewModel",
                    "fetchArticleList failed: ${response.code()} - ${response.message()}"
                )
            }
        } catch (e: Exception) {
            Log.e("ArticleViewModel", "fetchArticleList exception: $e")
        }
    }

}
